package com.visu.common.ip;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;

import com.visu.common.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Created by 程振奇 on 2017/11/29.
 * @version 1.0
 * @ClassName: IPUtils
 * @Desc: Ip工具类
 * @history v1.0
 */
public class IPUtils {


    public final static Log log = LogFactory.getLog(IPUtils.class);

    /**
     * 获取ip
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");

        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }


    /**
     * 获取所属地
     *
     *
     * @param ip
     * @return
     */
    public static AliIpDataBean getIPbelongAddress(String ip) {

        try {
            //淘宝提供的服务地址
            String context = sendGet("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
            if (StringUtils.isEmpty(context)) {
                return null;
            }
            IPUtilsResultBean ipUtilResultBean = JsonUtils.json2Obj(context, IPUtilsResultBean.class);
            if (ipUtilResultBean.getCode() == 0) {
                return ipUtilResultBean.getData();
            }

        } catch (Exception e) {
            log.error("请求淘宝ip接口出现异常", e);
        }
        return null;
    }


    /**
     * 发送get请求
     *
     * @param urlStr
     * @return
     */
    private static String sendGet(String urlStr) {

        try {

            URL url = new URL(urlStr);
            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

            httpCon.setConnectTimeout(3000);
            httpCon.setDoInput(true);
            httpCon.setRequestMethod("GET");

            int code = httpCon.getResponseCode();

            if (code == 200) {
                return streamConvertToSting(httpCon.getInputStream());
            }
        } catch (Exception e) {
            log.error("获取IP所属地址出错", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 流转化成String
     *
     * @param is
     * @return
     */
    private static String streamConvertToSting(InputStream is) {

        String tempStr = "";
        try {

            if (is == null) {
                return null;
            }
            ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
            byte[] by = new byte[1024];
            int len = 0;
            while ((len = is.read(by)) != -1) {
                arrayOut.write(by, 0, len);
            }
            tempStr = new String(arrayOut.toByteArray(), "UTF-8");

        } catch (IOException e) {
            log.error("转化出错", e);
        }
        return tempStr;
    }


}